/**
 * Created by XianTao on 2016/11/7
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.wechat.admin.api.restful;

import org.lego.handle.exception.ExtraInvalidParameterException;
import org.lego.jpa.base.util.DynamicSpecifications;
import org.lego.jpa.base.util.ServletUtil;
import org.lego.jpa.base.vo.ResultVo;
import org.lego.wechat.base.configuration.ConstantMessageKey;
import org.lego.wechat.base.entity.WxCorp;
import org.lego.wechat.base.service.WxCorpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import java.security.InvalidParameterException;

@RestController
@RequestMapping(value = "/admin/wechat/corp", method = RequestMethod.POST)
public class WxCorpAdminRestful {
    @Autowired
    private WxCorpService wxCorpService;

    @RequestMapping(value = "/list")
    public ResultVo<Page<WxCorp>> list(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                                       @RequestParam(value = "rows", defaultValue = "10") int pageSize,
                                       ServletRequest request) {
        PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, ServletUtil.getParametersStartingWithSort(request));
        Specification<WxCorp> specification = DynamicSpecifications.buildSpecification(
                ServletUtil.getParametersStartingWithSearch(request), WxCorp.class);
        return new ResultVo<Page<WxCorp>>(wxCorpService.findAll(specification, pageRequest));
    }

    @RequestMapping(value = "/insertOne")
    public ResultVo<WxCorp> insertOne(@RequestBody WxCorp wxCorp) {
        return new ResultVo<WxCorp>(wxCorpService.saveAndFlush(wxCorp));
    }

    @RequestMapping(value = "/updateOne")
    public ResultVo<WxCorp> updateOne(@RequestBody WxCorp wxCorp) {
        if (StringUtils.isEmpty(wxCorp.getId())) {
            throw new InvalidParameterException(ConstantMessageKey.WX_CORP_NEED_PARAM_ID);
        }
        WxCorp currentOne = wxCorpService.findOne(wxCorp.getId());
        if (currentOne == null) {
            throw new ExtraInvalidParameterException(ConstantMessageKey.WX_CORP_NOT_FOUND_BY_ID, wxCorp.getId());
        }
        //TODO: update entity
        return new ResultVo<WxCorp>(wxCorpService.saveAndFlush(currentOne));
    }
}
